<template>
  <a-row id="globalHeader" class="grid-demo" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../assets/oj_logo2.png" alt="logo" />
            <div class="title">OJ判题系统</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <!---------------头像区域------------------------------>
    <a-col flex="100px" style="margin-right: 20px">
      <a-popover v-if="userName != '未登录'">
        <a-avatar id="avatar" :size="60" class="avatar" @click="clickAvatar">
          {{ userName }}
        </a-avatar>
        <template #content>
          <!--设置功能选择框在登录的情况下才显示-->
          <a-space direction="vertical" size="small">
            <div class="linkContainer">
              <a-link class="linkStyle">
                <template #icon>
                  <icon-home />
                </template>
                个人中心
              </a-link>
            </div>
            <div class="linkContainer">
              <a-link class="linkStyle" href="/user/login">
                <template #icon>
                  <icon-user />
                </template>
                切换账号
              </a-link>
            </div>
            <div class="linkContainer">
              <a-link class="linkStyle" @click="logout">
                <template #icon>
                  <icon-export />
                </template>
                退出登录
              </a-link>
            </div>
          </a-space>
        </template>
      </a-popover>
      <a-avatar
        id="avatar"
        v-else
        :size="60"
        class="avatar"
        @click="clickAvatar"
      >
        {{ userName }}
      </a-avatar>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import tippy from "tippy.js";
import message from "@arco-design/web-vue/es/message";

const router = useRouter();
const store = useStore();
//设置为默认主页
const selectedKeys = ref(["/"]);
/**
 * 用户名
 */
const userName = computed(() => {
  return store.state.user.loginUser?.userName || "未登录";
});

// 展示在菜单的路由数组，使用computed，根据用户登录的改变响应式重新计算展示路由菜单
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    //根据权限过滤菜单
    //store.state.user.loginUser要写在computed内部，
    // 如此computed才会追踪这个登录用户状态的变化，并且根据这个值的变化响应式重新计算
    if (!checkAccess(store.state.user.loginUser, item.meta?.access as string)) {
      return false;
    }
    return true;
  });
});

//路由跳转后,更新选中的菜单栏
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});
const doMenuClick = (key: string) => {
  router.push({
    path: key,
  });
};
const clickAvatar = () => {
  if (userName?.value != "未登录" && userName?.value != null) {
    message.warning("个人中心功能开发中");
    // router.push({
    //   path: "/user/profile",
    // });
  } else {
    router.push({
      path: "/user/login",
    });
  }
};
var instance: any | null = null;

/**
 * 钩子函数挂载
 */
onMounted(() => {
  console.log();
});

/**
 * 监听用户登录状态变化, 如果用户已登录，则销毁 tippy 实例，否则创建新的 tippy 实例
 */
watch(
  userName,
  (newVal) => {
    //等待 DOM 更新后再执行
    nextTick(() => {
      if (newVal && newVal !== "未登录") {
        if (instance && Array.isArray(instance) && instance[0]) {
          instance[0].destroy();
        }
      } else if (newVal === "未登录" || !newVal) {
        instance = tippy("#avatar", {
          content: "前往登录",
        });
      }
    });
  },
  {
    // 立即执行一次
    immediate: true,
  }
);
/**
 * 退出登录
 */
const logout = () => {
  store.dispatch("user/logout").then(() => {
    message.success("退出成功");
  });
};
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #444;
  margin-left: 16px;
  font-size: 20px;
}

.avatar {
  cursor: pointer;
}

.avatar:hover {
  box-shadow: #dddddd 1px 1px 5px;
  scale: 1.05;
}

.logo {
  width: 60px;
}

.linkStyle {
  color: black;
}

.linkContainer {
  padding: 5px 10px 5px 10px;
  border-radius: 5px;
  text-align: center;
  cursor: pointer;
}

.linkContainer:hover {
  background: #f2f3f5;
  color: red;
}

.arco-icon {
  font-size: 20px;
}
</style>
